import 'dart:io';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/common_vo/common_pagination_vo.dart';
import 'package:xinxuan/vo/order_aggregates_vo.dart';
import 'package:open_file/open_file.dart';

class SeckillOrderSummaryPageController extends GetxController {
  
  CancelToken? cancelToken;
  static final String folderName = 'downloadFile';
  /// 文件保存位置
  var storagePath = ''.obs;
  /// 下载进度
  var percentChange = 0.0.obs;

  var orderAggregatesVo = OrderAggregatesVo(
    data: [],
    meta: OrderAggregatesMeta(
      pagination: CommonPagination(
        total: 0,
        currentPage: 1
      )
    )
  ).obs;

  var openControllerArr = [].obs;

  @override
  void onReady() async {
    getOrderAggregates();
    Directory storageDir = await getApplicationDocumentsDirectory();
    storagePath.value = storageDir.path + '/$folderName';
    super.onReady();
  }

  /// 获取秒杀未付款汇总
  getOrderAggregates() async {
    orderAggregatesVo.value.meta!.pagination!.currentPage = 1;
    OrderAggregatesVo tempVo = await HttpUtilService.getOrderAggregates(page: orderAggregatesVo.value.meta!.pagination!.currentPage!);
    tempVo.data!.forEach((item) {
      item.openStatus = 0;
    });
    orderAggregatesVo.value = tempVo;
    update();
  }

  /// 加载更多汇总订单
  onloadOrderAggregates() async {
    if (orderAggregatesVo.value.meta!.pagination!.total! <= orderAggregatesVo.value.data!.length) {
      return;
    }
    orderAggregatesVo.value.meta!.pagination!.currentPage = orderAggregatesVo.value.meta!.pagination!.currentPage! + 1;
    OrderAggregatesVo tempVo = await HttpUtilService.getOrderAggregates(page: orderAggregatesVo.value.meta!.pagination!.currentPage!);
    tempVo.data!.forEach((item) {
      item.openStatus = 0;
    });
    orderAggregatesVo.value.data!.addAll(tempVo.data!);
    update();
  }

  /// 下载文件
  downloadFile() async {
    DateTime dateTime = DateTime.now();
    String name = '${dateTime.year}${dateTime.month}${dateTime.day}${dateTime.hour}${dateTime.minute}${dateTime.second}汇总报表.xlsx';
    EasyLoading.show();
    cancelToken = CancelToken();
    Directory storageDir = await getApplicationDocumentsDirectory();
    int code = await HttpUtilService.downloadFile(
      // urlPath: url, 
      name: '${storageDir.path}/$folderName/$name',
      percentChange: (double value) {
        print('value: $value');
      },
      cancelToken: cancelToken!
    );
    EasyLoading.dismiss();
    if (code != 0) {
      OpenFile.open('${storagePath.value}/$name');
    }
  }

  // /// 打开与关闭
  // changeOpenStatus(int index) {
  //   orderAggregatesVo.value.data![index].openStatus = orderAggregatesVo.value.data![index].openStatus == 0 ? 1 : 0;
  //   update();
  // }

}